package com.atguigu.study.ref;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @auther zzyy
 * @create 2024-12-04 20:38
 */
public class ReflectionDemo
{
    public static void main(String[] args)throws Exception
    {
        //accessField();

        //accessSetField();

        accessMethod();

        //invokeMethod();

    }

    private static void invokeMethod() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException
    {
        String s0 = "Hello world";
        String r0 = s0.substring(6); // "world"

        // String对象:
        String s = "Hello world";
        // 获取String substring(int)方法，参数为int:
        Method m = s.getClass().getMethod("substring", int.class);
        // 在s对象上调用该方法并获取结果:
        String r = (String) m.invoke(s, 6);
        // 打印调用结果:
        System.out.println(r); // "world"
    }



    private static void accessMethod() throws NoSuchMethodException
    {
        Class stdClass = Student.class;
        // 获取public方法getScore，参数为String:
        System.out.println(stdClass.getMethod("getScore", String.class));
        // 获取继承的public方法getName，无参数:
        System.out.println(stdClass.getMethod("getName"));
        // 获取private方法getGrade，参数为int:
        System.out.println(stdClass.getDeclaredMethod("getGrade", int.class));
    }

    private static void accessSetField() throws Exception
    {
        Dog dog = new Dog("哈士奇");
        System.out.println(dog.getDogName()); // "哈士奇"
        Class c = dog.getClass();
        Field f = c.getDeclaredField("dogName");
        f.setAccessible(true);
        f.set(dog, "泰迪");
        System.out.println(dog.getDogName()); // "泰迪"
    }

    private static void accessField() throws NoSuchFieldException
    {
        Class   stdClass = Student.class;
                stdClass = new Student().getClass();
        // 获取public字段"score":
        System.out.println(stdClass.getField("score"));
        // 获取继承的public字段"name":
        System.out.println(stdClass.getField("name"));
        // 获取private字段"grade":
        System.out.println(stdClass.getDeclaredField("grade"));
    }

    public <T> T getObject(Class<T> clazz) throws Exception
    {
        T t = clazz.newInstance();
        return t;
    }
}

class Person {
    public String name;
    public String getName() {
        return "Person";
    }
}
class Student extends Person {
    public int score;
    private int grade;

    public int getScore(String type) {
        return 99;
    }

    private int getGrade(int year) {
        return 1;
    }
}
class Dog
{
    private String dogName;

    public Dog(String dogName) {
        this.dogName = dogName;
    }

    public String getDogName() {
        return this.dogName;
    }
}